package com.fly.locks.distributed.database;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * ScheduleJob
 * 
 * @author 00fly
 * @version [版本号, 2022年11月30日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class ScheduleJob
{
    DataUpdateLock updateLock;
    
    private String serverIp;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    // 初始化代码块
    {
        try
        {
            serverIp = InetAddress.getLocalHost().getHostAddress();
        }
        catch (UnknownHostException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 初始化
     */
    @PostConstruct
    public void init()
    {
        updateLock = new DataUpdateLock("job001", jdbcTemplate);
    }
    
    @Scheduled(cron = "0/10 * * * * ?")
    public void run()
    {
        try
        {
            if (updateLock.getLock(9L))
            {
                log.info("[{}] #### hello world ***********", serverIp);
                return;
            }
            log.info("[{}] 没抢到，骂骂咧咧的走了......", serverIp);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
